package io.github.shenbinglife.jlock;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

public class JReadWriteLock implements ReadWriteLock {

    private List<ReadWriteLock> locks;

    public JReadWriteLock(ReadWriteLock... parents) {
        if (parents == null || parents.length == 0) {
            throw new IllegalArgumentException("locks can not be empty");
        } else {
            this.locks = Arrays.asList(parents);
        }
    }

    public JReadWriteLock(List<ReadWriteLock> parents) {
        if (parents == null || parents.isEmpty()) {
            throw new IllegalArgumentException("locks can not be empty");
        } else {
            this.locks = new ArrayList<>(parents);
        }
    }

    @Override
    public Lock readLock() {
        List<Lock> readLocks = new ArrayList<>();
        for (ReadWriteLock lock : locks) {
            readLocks.add(lock.readLock());
        }
        return new JLock(readLocks);
    }

    @Override
    public Lock writeLock() {
        List<Lock> writeLocks = new ArrayList<>();
        for (ReadWriteLock lock : locks) {
            writeLocks.add(lock.writeLock());
        }
        return new JLock(writeLocks);
    }

    public List<ReadWriteLock> getLocks() {
        return new ArrayList<>(locks);
    }
}
